//设置根路径
axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net'

//获取元素
const tb = document.querySelector('#tb')
// 添加列表
const goodlists = () => {
  axios.get('/api/getbooks').then(({ data: res }) => {
    const { data } = res
    console.log(res)
    const html = data
      .map((item) => {
        return `<tr>
           <td>${item.id}</td>
           <td>${item.bookname}</td>
           <td>${item.author}</td>
           <td>${item.publisher}</td>
           <td><a href="#" data-id="${item.id}">删除</a></td>
         </tr>`
      })
      .join('')
    tb.innerHTML = html
  })
}

goodlists()
// 添加图书
// 获取元素
const form = document.querySelector('#bookForm')
form.addEventListener('submit', function (e) {
  e.preventDefault()
  const data = serialize(form, { hash: true })
  console.log(data)
  axios.post('/api/addbook', data).then(({ data: res }) => {
    alert(res.msg)
    if (res.status !== 201) return
    form.reset()
    goodlists()
  })
})
// 删除图书
tb.addEventListener('click', function (e) {
  if (e.target.tagName === 'A') {
    let id = e.target.dataset.id
    axios.get('/api/delbook?id=' + id).then(({ data: res }) => {
      console.log(res)
      goodlists()
    })
  }
})
// 筛选
const btn = document.querySelector('#btnAnd')
btn.addEventListener('click', function () {
  const data = serialize(form, { hash: true })
  console.log(data)
  const bookname = data.bookname
  const author = data.author
  const publisher = data.publisher
  axios({
    url: '/api/getbooks',
    method: 'GET',
    params: {
      bookname,
      author,
      publisher,
    },
  }).then(({ data: res }) => {
    const { data } = res
    console.log(res)
    const html = data
      .map((item) => {
        return `<tr>
           <td>${item.id}</td>
           <td>${item.bookname}</td>
           <td>${item.author}</td>
           <td>${item.publisher}</td>
           <td><a href="#" data-id="${item.id}">删除</a></td>
         </tr>`
      })
      .join('')
    tb.innerHTML = html
  })
})
